#include<bits/stdc++.h>
using namespace std;

//Definition for singly-linked list.
struct ListNode {
	int val;
	ListNode* next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
	ListNode* detectCycle(ListNode* head) {
		if (!head || !head->next || !head->next->next) return nullptr;
		ListNode* fptr = head, * sptr = head;
		while (fptr) {
			if (!fptr->next)return nullptr;
			fptr = fptr->next->next;
			sptr = sptr->next;
			if (fptr = sptr) {
				fptr = head;
				while (fptr!=sptr) {
					sptr = sptr->next;
					fptr = fptr->next;
				}
				return sptr;
			}
		}
		return nullptr;
	}
};